<!--  -->
<template>
  <div class="template_text">
    <div class="toText">{{scriptItem.label}}</div>
    <el-input v-model="dataForm[scriptItem.text]"
            :counter="scriptItem.counter"
            :rules="scriptItem.rules"
            :label="scriptItem.label"
            @input="inputChange"
            @blur="getCursor"
            persistent-hint
            :placeholder="scriptItem.hint"
            required></el-input>
    <el-tooltip :open-delay="1000" class="item" effect="dark" content="Insert a token" placement="top">
      <el-popover placement="top"
                  width="380"
                  v-model="insertTokenPopover">
        <div v-if="!isShowChild&&!isShowChildDrillThrough" style="color:#000;font-size:16px;font-weight: 600;margin-bottom:10px">Dynamic Token</div>
        <div v-else class="cursor_pointer" style="color:#000;font-size:16px;font-weight: 600;margin-bottom:10px" @click="gotoback"><i class="el-icon-arrow-left"></i>&nbsp;&nbsp;Field Name</div>
        <el-input v-if="!isShowChild&&!isShowChildDrillThrough" v-model="searchToken"
                  prefix-icon="el-icon-search"
                  placeholder="search"
                  @input="getFilterTokenList"
                  size="small"
                  style="margin-bottom:10px;"></el-input>
        <el-input v-if="isShowChild||isShowChildDrillThrough" v-model="searchTokenchild"
                  prefix-icon="el-icon-search"
                  placeholder="search"
                  @input="getFilterTokenchildList"
                  size="small"
                  style="margin-bottom:10px;"></el-input>
        <div v-if="isTipsShow&&!isShowChild&&!isShowChildDrillThrough"  style="height:50px;backgroundColor:#E6F7FF;">
          <div style="float:left;width:90%;color:#138DC7;line-height:20px;padding:5px;padding-left:9px;word-break: break-word;">Add dynamic tokens from data source and drill through used in this massage.</div>
          <i @click="isTipsShow=false" class="el-icon-close cursor_pointer" style="float:right;color:#138DC7;margin:8px 9px 0 0"></i>
        </div>
        <el-alert v-if="!(filterTokenList&&filterTokenList.length>0&&filterTokenList[0].fieldsList.length>0)&&!drillThroughFieldsListarr.length>0" style="margin-top:10px" :closable="false" center title="No matching data" type="info"></el-alert>
        <div class="token-list" v-if="filterTokenList&&filterTokenList.length>0&&filterTokenList[0].fieldsList.length>0">
          <div class="token-list-item"
              v-for="(item, index) in filterTokenList"
              :key="index">
            <!-- <el-divider v-if="!isShowChild" class="split-line"></el-divider> -->
            <div v-if="!isShowChild&&!isShowChildDrillThrough">
              <div class="group-title" style="backgroundColor:#F0F0F0;padding-left:9px;" :style="{'margin-top':isTipsShow?'10px':0}">Data source fields</div>
              <div style="max-height: 150px;overflow:auto">
                <div class="group-item"
                    v-for="(its, ii) in item.fieldsList"
                    :key="ii"
                    @click="its.type === 'user' ? openChild(its) : clickToken(its)"><span :style="{'font-weight':its.type === 'user'? '600' : '400'}">{{ its.type === 'user' ? its.label.replace(/[\{\}]/g,'') : its.label}}</span>
                    <i v-if="its.type === 'user'" class="el-icon-arrow-right" style="float:right;padding-top:10px"></i>
                </div>
              </div>
            </div>
            <div v-if="isShowChild&&!isShowChildDrillThrough">
              <div class="group-item"
                v-for="its in filteruserfieldsList"
                  :key="its.value"
                  @click="clickTokenchild(its)">{{ its.label }}
              </div>
            </div>
          </div>
        </div>
        <div class="token-list" v-if="drillThroughFieldsListarr.length>0">
          <div class="token-list-item">
            <div v-if="!isShowChild&&!isShowChildDrillThrough">
              <div class="group-title" style="backgroundColor:#F0F0F0;padding-left:9px;">Drill Through fields</div>
              <div style="height: 150px;overflow:auto">
                <div class="group-item11"
                    v-for="(its, ii) in drillThroughFieldsListarr"
                    :key="ii"
                    @click="openChildDrillThrough(its,ii)">
                     <ZTooltip :content="its.datasetName"
                              :line="1"
                              placement="right">
                              <span style="font-weight:600">{{its.datasetName}}</span>
          
                              </ZTooltip>
                   
                    <i class="el-icon-arrow-right" style="float:right;padding-top:10px"></i>
                </div>
              </div>
            </div>
            <div v-if="!isShowChild&&isShowChildDrillThrough" style="max-height:442px;overflow:auto">
              <div class="group-item"
                v-for="its in childDrillThroughfieldsList"
                  :key="its.value"
                  @click="clickTokenchild(its,true)">{{ its.label }}
              </div>
            </div>
          </div>
        </div>
        <el-button size="mini"
                  type="primary"
                  plain
                  slot="reference"
                  v-if="showInsertTokenBtn"
                  style="padding:7px;border:none;">
          <span class="cuifont icon_insert_token"
                style="fontSize:14px;"></span>
        </el-button>
      </el-popover>
    </el-tooltip>
  </div>
</template>

<script>
import mixinTypeViewModule from '@/mixins/script-type-view-module'
import { debounce } from 'lodash'
import ZTooltip from '@/components/storybook/z-tooltip'
export default {
  mixins: [mixinTypeViewModule],
  inject: {botInfo:{default:()=>{}}},
  components: { ZTooltip },
  data () {
    return {
      startPos: null,
      endPos: null,
      insertTokenPopover: false,
      isShowChild: false,
      isShowChildDrillThrough: false,
      searchToken: null,
      searchTokenchild: null,
      isTipsShow: true,
      filterTokenList: [],
      drillThroughFieldsListarr: [],
      filteruserfieldsList: [],
      childDrillThroughfieldsList: [],
      drillThroughFieldsList: [],
      childDrillThroughfieldsListarr: [],
      fatherfield: null,
      userfieldsList: [{ label: '{headUrl}', value: 'headUrl' },
        { label: '{email}', value: 'email' },
        { label: '{firstName}', value: 'firstName' },
        { label: '{lastName}', value: 'lastName' },
        { label: '{fullName}', value: 'fullName' } ]
    }
  },
  watch: {
    isShowChild (val) {
      if (!val) {
        this.searchTokenchild = null
        this.resetFilterTokenchildList(this.searchTokenchild)
      }
    },
    isShowChildDrillThrough (val) {
      if (!val) {
        this.searchTokenchild = null
        this.resetFilterTokenchildList(this.searchTokenchild)
      }
    },
    insertTokenPopover: {
      handler: function (val) {
        if (val) {
          this.isTipsShow = true
          document.addEventListener('mousedown', this.mouseDownListener)
        } else {
          document.removeEventListener('mousedown', this.mouseDownListener)
          this.searchToken = null
          this.resetFilterTokenList(this.searchToken)
          this.searchTokenchild = null
          this.resetFilterTokenchildList(this.searchTokenchild)
          this.isShowChild = false
          this.isShowChildDrillThrough = false
        }
      },
      immediate: true
    },
    editTemplatePopover: {
      handler: function (val) {
        if (val) {
          document.addEventListener('mousedown', this.mouseDownListener)
        } else {
          document.removeEventListener('mousedown', this.mouseDownListener)
        }
      },
      immediate: true
    },
    templateId (val) {
      if (val) {
        try {
          this.dataForm[this.scriptItem.text] = this.selectDataObj[`${this.scriptItem.text}ListsOrigin`].find(e => e[this.scriptItem.fieldValue] === this.templateId)[this.scriptItem.templateFields]
        } catch (error) { }
      }
    }
  },
  computed : {
    showInsertTokenBtn () {
      if(this.scriptItem && this.scriptItem.showInsertToken === null){
        return this.scriptItem.showInsertToken
      }
      if(this.scriptItem && this.scriptItem.showInsertToken)
      {
        return true
      }
      else{
        return false
      }      
    }
  },
  created () {
    this.initTempSelectDatasetKey()
    if (this.botInfo() && this.botInfo().triggerType === 'Stream') {
      this.getTemplateParamsList()
    } else {
      this.getTokenList()
    }
    this.filteruserfieldsList = this.userfieldsList
  },
  methods: {
    inputChange () {
      this.$forceUpdate()
    },
    initTempSelectDatasetKey () {
      if (!this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`]) this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`] = []
    },
    gotoback () {
      this.isShowChild = false
      this.isShowChildDrillThrough = false
    },
    openChild (its) {
      this.fatherfield = its.value
      this.isShowChild = true
    },
    getCursor (e) {
      this.startPos = e.target.selectionStart
      this.endPos = e.target.selectionEnd
    },
    clickToken (its) {
      if (!(this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`].find(item => item.field === its.value))) {
        this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`].push({
          field: its.value,
          dbType: its.type
        })
      }
      this.insertFields(its.value)
    },
    insertFields (value) {
      if (!value) {
        return false
      }
      value = ` {${value}}`
      if (!this.startPos && !this.endPos) {
        this.dataForm[this.scriptItem.text] = this.dataForm[this.scriptItem.text] + value
        return
      }
      this.dataForm[this.scriptItem.text] = this.dataForm[this.scriptItem.text].substring(0, this.startPos) + value +
      this.dataForm[this.scriptItem.text].substring(this.endPos, this.dataForm[this.scriptItem.text].length)
    },
    mouseDownListener (event) {
      if (!event.target.closest('.block-model-dialog')) {
      } else {
        this.insertTokenPopover = false
        this.editTemplatePopover = false
      }
    },
    resetFilterTokenchildList (val) {
      let searchVal = val || this.searchTokenchild
      if (searchVal) {
        let copyData = this._.cloneDeep(this.userfieldsList)
        copyData = copyData.filter(its => its.label.toLowerCase().includes(searchVal.toLowerCase()))
        this.filteruserfieldsList = copyData
      } else {
        this.filteruserfieldsList = this.userfieldsList
      }
      if (searchVal) {
        let copyData = this._.cloneDeep(this.childDrillThroughfieldsListarr)
        copyData = copyData.filter(its => its.label.toLowerCase().includes(searchVal.toLowerCase()))
        this.childDrillThroughfieldsList = copyData
      } else {
        this.childDrillThroughfieldsList = this.childDrillThroughfieldsListarr
      }
    },
    getFilterTokenList: debounce(function (val) {
      this.resetFilterTokenList(val)
    }, 800),
    getFilterTokenchildList: debounce(function (val) {
      this.resetFilterTokenchildList(val)
    }, 800),
    clickTokenchild (its, isDrillThrough) {
      if (isDrillThrough) {
        this.insertFields(`${this.fatherfield}#${its.value}`)
      } else {
        this.insertFields(`${this.fatherfield}.${its.value}`)
      }
    },
    openChildDrillThrough (its, index) {
      this.fatherfield = its.datasetName
      this.isShowChildDrillThrough = true
      this.childDrillThroughfieldsListarr = this.drillThroughFieldsListarr[index].data
      this.childDrillThroughfieldsList = this.childDrillThroughfieldsListarr
    },
    getTemplateParamsList () {
      var _self = this
      _self.$interface.schedule.getTemplateFieldsListApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return _self.$message.error(res.msg)
          }
          var name
          if (_self.botInfo().sysBotScriptList.length === 1) {
            name = _self.botInfo().sysBotScriptList[0].paramsValue.type
          } else {
            var block = _self.botInfo().flowSetting.find(item => item.id === 0)
            var sysbot = _self.botInfo().sysBotScriptList.find(item => item.scriptId === block.blockId)
            name = sysbot.paramsValue.type
          }
          var result = res.data.find(i => i.name === name)
          let tempList = []
          result.info.forEach(item => {
            tempList.push({
              label: `{${item.key}}`,
              value: item.key,
              type: item.type
            })
          })
          tempList.push({
            label: `{email}`,
            value: 'email',
            type: 'text'
          })
          tempList.push({
            label: `{firstName}`,
            value: 'firstName',
            type: 'text'
          })
          tempList.push({
            label: `{lastName}`,
            value: 'lastName',
            type: 'text'
          })
          tempList.push({
            label: `{fullName}`,
            value: 'fullName',
            type: 'text'
          })
          this.tokenList.push({
            name: this.$store.state.bot.name,
            fieldsList: tempList
          })
          this.$nextTick(() => {
            this.resetFilterTokenList()
          })
        }).catch(() => { })
    },
    resetFilterTokenList (val) {
      let searchVal = val || this.searchToken
      if (searchVal) {
        let copyData = this._.cloneDeep(this.tokenList)
        for (let i = 0; i < copyData.length; i++) {
          copyData[i].fieldsList = copyData[i].fieldsList.filter(its => its.label.toLowerCase().includes(searchVal.toLowerCase()))
        }
        this.filterTokenList = copyData
      } else {
        this.filterTokenList = this.tokenList
      }
      if (searchVal) {
        let copyData = JSON.parse(JSON.stringify(this.drillThroughFieldsList))
        copyData = copyData.filter(its => its.datasetName.toLowerCase().includes(searchVal.toLowerCase()))
        this.drillThroughFieldsListarr = copyData
      } else {
        this.drillThroughFieldsListarr = this.drillThroughFieldsList
      }
    },
    getTokenList () {
      let id = this.$store.state.bot.id
      let type = this.$store.state.bot.type
      this.tokenList = []
      if (!id) {
        return
      }
      const params = {}
      type === 'dataset' && (params['datasetId'] = id)
      type === 'widget' && (params['gadgetId'] = id)
      params.showColumn = true
      this.$interface.reports.getFieldsListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.tokenList = []
            return false
          }
          if (res.querySelectedColumns) {
            this.dataForm.resultValue = res.querySelectedColumns
            this.drillThroughFieldsList = res.querySelectedColumns
            this.drillThroughFieldsList.forEach(item => {
              item.data.forEach(its => {
                its.label = `{${its.alias}}`
                its.value = its.alias
              })
            })
            this.drillThroughFieldsListarr = this.drillThroughFieldsList
          }
          let tempList = []
          res.data.forEach(item => {
            if (item.type === 'user') {
              tempList.unshift({
                label: `{${item.name}}`,
                value: item.name,
                type: item.type
              })
            } else {
              tempList.push({
                label: `{${item.name}}`,
                value: item.name,
                type: item.type
              })
            }
          })
          this.tokenList.push({
            name: this.$store.state.bot.name,
            fieldsList: tempList
          })
          this.$nextTick(() => {
            this.resetFilterTokenList()
          })
        }).catch(() => {
          this.tokenList = []
        })
    }
  }
}
</script>

<style lang="scss">
.template_text{
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-top: 6px;
  margin-bottom: 10px;
  padding: 5px 0;
  padding-right: 10px;
  .el-input{
    flex: 1;
    input{
      margin-left: 0 !important;
    }
  }
  .el-input__inner{
    border: 0;
  }
  .el-tooltip{
    width: 30px;
  }
}
</style>
<style scoped lang='scss'>
.cursor_pointer {
  cursor:pointer
}
.popover-footer-btn {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.token-list {
  &-item {
    .group-title {
      color: rgba(0, 0, 0, 0.5);
      font-size: 12px;
      width: 100%;
      height: 30px;
      line-height: 30px;
      margin-top: 10px;
    }
    .group-item {
      height: 34px;
      line-height: 34px;
      padding: 0 10px 0 19px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
      &:hover {
        background: #f5f7fa;
      }
    }
    .group-item11 {
      display: flex;
      height: 34px;
      line-height: 34px;
      padding: 0 10px 0 19px;
      cursor: pointer;
      &:hover {
        background: #f5f7fa;
      }
    }
  }
}
</style>
